#include "protocol.h"

u8 Protocol::Data_Receive_Precess(u8 RxData)
{
	static u8 RxState = 0, cnt = 0, sum, Len;
	switch (RxState) {
	case 0:  //帧头校验
		if (RxData == '>') {
			sum = RxData;
			RxState = 1;
		}
		break;
	case 1:  //功能字校验与保存
		sum += RxData;
		Fcn = RxData;
		RxState = 2;
		break;
	case 2:  //数据长度校验与保存
		if (RxData <= 12)
		{
			sum += RxData;
			Len = RxData;
			RxState = 3;
		}
		else
		{
			sum = 0;
			RxState = 0;
		}
		break;
	case 3:  //临时保存待用数据
		sum += RxData;
		ValidData[cnt++] = RxData;
		if (cnt >= Len)
			RxState = 4;
		break;
	case 4:  //匹配校验和
		RxState = 0;
		cnt = 0;
		if (sum != RxData) {
			sum = 0;
			return 2;  //数据帧出错
		}
		sum = 0;
		return 0;  //收到了正确的数据帧
	default:
		RxState = 0;
		sum = 0;
		cnt = 0;
		return 2;  //数据帧出错
	}
	return 1;  //数据帧尚未接收完成
}

u8 Protocol::Send_u8_Data(u8 data, u8 fcn)
{
    char DataToSend[5];
    DataToSend[0]=0x3C;
    DataToSend[1]=fcn;
    DataToSend[2]=0x01;
    DataToSend[3]=data;
    DataToSend[4]=0x3D+data+fcn;
    write(DataToSend, 5);
    return 5;
}

u8 Protocol::Send_u8_Data(char* data, u8 fcn, u8 len)
{
	u8 i, cnt = 0, sum = 0x3C + fcn + len;
	char DataToSend[10];
	DataToSend[cnt++] = 0x3C;
	DataToSend[cnt++] = fcn;
	DataToSend[cnt++] = len;
	for (i = 0; i < len; ++i) {
		DataToSend[cnt++] = data[i];
		sum += data[i];
	}
	DataToSend[cnt++] = sum;
	write(DataToSend, cnt);
	return cnt;
}

u8 Protocol::Send_s16_Data(s16* data, u8 fcn, u8 len)
{
	u8 i, cnt = 0, sum = 0x3C + fcn + (len << 1);
	char DataToSend[16];
	u8 datatemp;
	DataToSend[cnt++] = 0x3C;
	DataToSend[cnt++] = fcn;
	DataToSend[cnt++] = len << 1;
	for (i = 0; i < len; ++i) {
		datatemp = BYTE1(data[i]);
		DataToSend[cnt++] = datatemp;
		sum += datatemp;
		datatemp = BYTE0(data[i]);
		DataToSend[cnt++] = datatemp;
		sum += datatemp;
	}
	DataToSend[cnt++] = sum;
	write(DataToSend, cnt);
	return cnt;
}
